import React, { useEffect, useReducer, useState } from "react";
import {
  Carousel,
  InputItem,
  Button,
  Grid,
  Card,
  Icon,
  Toast,
} from "antd-mobile";
import { BASEURL, reqSwiper, reqGroups, reqNews } from "../../api";
import { getChooseCity, cityKey } from "../../utils";

import List from "../../components/List";
import nav1 from "../../assets/images/nav-1.png";
import nav2 from "../../assets/images/nav-2.png";
import nav3 from "../../assets/images/nav-3.png";
import nav4 from "../../assets/images/nav-4.png";

import "./index.scss";

export default function Index(props) {
  const { history } = props;

  const [chooseCityInfo, setChooseCityInfo] = useState({});
  const [localCityInfo] = useState(JSON.parse(localStorage.getItem(cityKey)));
  const [reqStatus, setReqStatus] = useState({
    getSwiper: false,
    getGroups: false,
    getNews: false,
  });

  // const loadingStatus={swiper:false,groups:false}

  const featureData = [
    {
      icon: (
        <div className="icon">
          <img src={nav1} alt="" />
        </div>
      ),
      text: "整租",
      path: "/home/find",
      params: { rentType: "true" },
    },
    {
      icon: (
        <div className="icon">
          <img src={nav2} alt="" />
        </div>
      ),
      text: "合租",
      path: "/home/find",
      params: { rentType: "false" },
    },
    {
      icon: (
        <div className="icon">
          <img src={nav3} alt="" />
        </div>
      ),
      text: "地图找房",
      path: "/map",
    },
    {
      icon: (
        <div className="icon">
          <img src={nav4} alt="" />
        </div>
      ),
      text: "去出租",
      path: "/manage",
    },
  ];
  const [state, dispatch] = useReducer(
    (state, action) => {
      let res = { ...state };
      switch (action.type) {
        case "swiper":
          res.swiper = action.data;
          return res;
        case "feature":
          res.featureData = action.data;
          return res;
        case "group":
          res.groupData = action.data;
          return res;
        case "news":
          res.newsData = action.data;
          return res;
        default:
          return state;
      }
    },
    { swiper: [], featureData: [], groupData: [], newsData: [] }
  );
  // const [loadingStatus, setLoadingStatus] = useState({swiper:false,groups:false})

  useEffect(() => {
    let timer = null;
    async function getSwiper() {
      let res = await reqSwiper();
      dispatch({ type: "swiper", data: res.body });
      setReqStatus({ ...reqStatus, getSwiper: true });
    }
    async function getGroups(area) {
      let res = await reqGroups({ area: area });
      let data = res.body;
      data = data.map((i) => {
        return {
          icon: (
            <div className="icon">
              <div className="info">
                <p style={{ fontWeight: "bold", color: "#000" }}>{i.title}</p>
                <p>{i.desc}</p>
              </div>
              <img src={BASEURL + i.imgSrc} alt="" />
            </div>
          ),
        };
      });
      dispatch({ type: "group", data });
      setReqStatus({ ...reqStatus, getGroups: false });
    }
    async function getNews(area) {
      let res = await reqNews({ area: area });
      let data = res.body;
      data = data.map((i) => {
        i.imgSrc = BASEURL + i.imgSrc;
        return i;
      });
      dispatch({ type: "news", data });
      setReqStatus({ ...reqStatus, getNews: false });
    }
    async function getCityInfo() {
      await new Promise((resolve) => {
        timer = setInterval(() => {
          let info = getChooseCity();
          if (info.name) {
            setChooseCityInfo(info);
            clearInterval(timer);
            timer = null;
            resolve();
          }
        }, 10);
      });
    }
    if (state.swiper.length === 0 && !reqStatus.getSwiper) {
      setReqStatus({ ...reqStatus, getSwiper: true });
      getSwiper();
    }
    if (state.groupData.length === 0 && !reqStatus.getGroups) {
      setReqStatus({ ...reqStatus, getGroups: true });
      getGroups({ area: chooseCityInfo.id });
    }
    if (state.newsData.length === 0 && !reqStatus.getNews) {
      setReqStatus({ ...reqStatus, getNews: true });
      getNews({ area: chooseCityInfo.id });
    }
    getCityInfo();
    return () => {
      clearInterval(timer);
      timer = null;
    };
  }, [state, chooseCityInfo, reqStatus]);

  return (
    <div>
      <div className="index-carousel">
        {state.swiper.length === 0 ? null : (
          <Carousel autoplay={true} infinite>
            {state.swiper.map((val) => (
              <img
                key={val.imgSrc}
                src={BASEURL + val.imgSrc}
                alt={val.alt}
                style={{ width: "100%", verticalAlign: "top", height: "200px" }}
                onLoad={() => {
                  window.dispatchEvent(new Event("resize"));
                }}
              />
            ))}
          </Carousel>
        )}

        <div className="index-selector">
          <InputItem clear placeholder="请输入小区或地址">
            <Button
              type="link"
              onClick={() =>
                history.push("/cityList", { cityName: localCityInfo.name })
              }
            >
              {chooseCityInfo.name ? (
                <span style={{ display: "flex", alignItems: "center" }}>
                  {chooseCityInfo.name}
                  <i className="iconfont icon-arrow" />
                </span>
              ) : (
                <span
                  style={{
                    fontSize: "12px",
                    display: "flex",
                    alignItems: "center",
                  }}
                >
                  <Icon type="loading"></Icon>定位中...
                </span>
              )}
            </Button>
          </InputItem>
          <div className="index-map" onClick={() => history.push("/map")}>
            <i className="iconfont icon-map"></i>
          </div>
        </div>
      </div>
      <div className="index-feature">
        <Grid
          data={featureData}
          hasLine={false}
          onClick={(icon) =>
            icon.path !== undefined
              ? history.push(icon.path, icon.params)
              : null
          }
        />
      </div>
      <div className="index-group">
        <Card>
          <Card.Header
            title={
              <span style={{ padding: "5px 0", fontWeight: "bold" }}>
                租房小组
              </span>
            }
            extra={
              <span onClick={() => Toast.info("暂无更多", 2, null, false)}>
                更多
              </span>
            }
          />
          <Card.Body>
            <div className="index-group-content">
              <Grid
                square={false}
                data={state.groupData}
                hasLine={false}
                columnNum={2}
                itemStyle={{
                  border: "5px solid #f4f4f4",
                  backgroundColor: "transparent",
                }}
              />
            </div>
          </Card.Body>
        </Card>
      </div>
      <div className="index-news">
        <Card>
          <Card.Header
            title={
              <span style={{ padding: "5px 0", fontWeight: "bold" }}>
                最新资讯
              </span>
            }
          />
          <Card.Body>
            <div className="index-news-content">
              <List list={state.newsData} />
            </div>
          </Card.Body>
        </Card>
      </div>
    </div>
  );
}
